package com.dataknife.core;

import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.dataknife.util.ConfigHandler;
import com.dataknife.core.AsyncController;
import com.dataknife.core.Event;
import com.dataknife.core.Process;
import com.dataknife.util.ArithUtil;
import com.dataknife.util.DateUtil;
import com.dataknife.util.StringUtil;

public class TimerPlugin extends Plugin
{
  private static final Logger logger = Logger.getLogger(DBReaderPlugin.class);

  private Timer timer;
  private TimerTask task;

  @Override
  public Event init(Event event)
  {
    logger.info("timer plugin init begin");
    ConfigHandler conf = (ConfigHandler)event.getContext();
    initTimer(conf);
    logger.info("timer plugin init end");
    return null;
  }

  private void initTimer(final ConfigHandler conf){
    timer = new Timer();
    task = new TimerTask() {
      @Override
      public void run() {
        Event e = new Event(conf,Process.SERVICE);
        logger.info("Timer begin to stat...");
        AsyncController.getInstance().startup(e);
      }
    };
  }

  @Override
  public Event service(Event event)
  {
    logger.info("timer plugin service begin");
//    AsyncController.getInstance().startup(event);
    ConfigHandler conf = (ConfigHandler)event.getContext();
    Map<String,Object> timerMap = conf.getTimerMap();
    String repeatTime = timerMap.get(conf.retime).toString();
    String period = timerMap.get(conf.period).toString();
    Date date = DateUtil.parseRepeatTime(repeatTime);
    if(date.before(new Date())){
      date = DateUtil.addDay(date, 1);
    }
    if (StringUtil.isNullOrBlank(period) || period.equalsIgnoreCase("0")) {
      timer.schedule(task, date);
      logger.info("timer plugin loading...");
    } else {
      period = ArithUtil.parseExp(period);
      timer.schedule(task, date, Long.valueOf(period));
      logger.info("timer plugin loading...");
    }
    logger.info("timer plugin service end");
    return null;
  }

  @Override
  public Event destroy(Event event)
  {
    if (task != null) {
      task.cancel();
    }
    if (timer != null) {
      timer.cancel();
    }
    return null;
  }

}
